package com.sanbi.erp.db.service;

import com.sanbi.common.util.JacksonUtil;
import com.sanbi.erp.core.dto.CategoryDto;
import com.sanbi.erp.core.system.ErrorEnum;
import com.sanbi.erp.db.config.BizException;
import com.sanbi.erp.db.dao.ProductMapper;
import com.sanbi.erp.db.domain.Product;
import com.sanbi.erp.db.util.CheckoutUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.sanbi.erp.db.dao.CategoryMapper;
import com.sanbi.erp.db.domain.Category;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryService{

    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private ProductMapper productMapper;


    public int deleteByPrimaryKey(Integer id) {
        return categoryMapper.deleteByPrimaryKey(id);
    }


    public int insert(Category record) {
        return categoryMapper.insert(record);
    }


    public int insertSelective(Category record) {
        record.setAddTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());
        record.setDeleted(false);
        return categoryMapper.insertSelective(record);
    }

    /**
     * 新增类目
     * @param body
     * {name 类目名称,type 0:1级类目 1:2级类目,pid 父类目id}
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertSelectiveByType(String body) {
        Category category = new Category();
        String name = JacksonUtil.parseString(body,"name");
        int type = JacksonUtil.parseInteger(body,"type");
        int pid = JacksonUtil.parseInteger(body,"pid");
        // 判断类目名称是否重复
        if (this.categoryMapper.selectByName(name) != null) {
            throw new BizException(ErrorEnum.ErrorCode.categoryNameRepetition);
        }
        // 如果是2级类目
        if (type != CheckoutUtil.TYPE_ZERO) {
            category.setPid(pid);
            category.setLevel("L2");
        }
        category.setNameCn(name);
        category.setAddTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setDeleted(false);
        return categoryMapper.insertSelective(category);
    }

    public Category selectByPrimaryKey(Integer id) {
        return categoryMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据名称模糊查询
     * @param nameCn 中文名称
     * @return
     */
    public List<CategoryDto> selectByLike(String nameCn) {
        // 获取1级类目
        List<Category> categoryList = categoryMapper.selectByLike();
//        List<Category> categoryListLOne = categoryList.stream().filter(item -> item.getLevel().equals("L1")).collect(Collectors.toList());
//        List<Category> categoryListLZero = categoryList.stream().filter(item -> item.getLevel().equals("L0")).collect(Collectors.toList());
        // 获取2级类目，模糊查询
        List<Category> categoryListTwo = categoryMapper.selectByLikeTwo(nameCn);
        //遍历一级类目
        List<CategoryDto> collect = categoryList.stream().map(parent -> {
            //查询二级目录
            List<Category> l2 = categoryListTwo.stream().filter(item -> item.getPid().equals(parent.getId())).collect(Collectors.toList());
            //遍历二级目录,将二级目录数据存入工具类中
            List<CategoryDto> childrenList = l2.stream().map(children -> new CategoryDto(children.getId(), children.getNameCn(), children.getIconUrl(), children.getPid(), null)).collect(Collectors.toList());
            //将一级类目及遍历后的二级目录存入parentList集合中
            return new CategoryDto(parent.getId(), parent.getNameCn(), parent.getIconUrl(), parent.getPid(), childrenList);
        }).collect(Collectors.toList());
//        List<Object> list = new ArrayList<>();
//        list.add(categoryListLZero.get(0));
//        list.add(collect);
        return collect;
    }

    /**
     * 获取所有二级类目
     * @return
     */
    public List<Category> selectAllByTwo() {
        return categoryMapper.selectByLikeTwo(null);
    }

    /**
     * 获取所有类目
     * @return
     */
    public List<Category> selectAllEasyExcel() {
        return categoryMapper.selectAllEasyExcel();
    }

    public int updateByPrimaryKeySelective(Category record) {
        return categoryMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 修改类目
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateByPrimaryKeySelectiveTwo(String body) {
        String name = JacksonUtil.parseString(body,"name");
        int id = JacksonUtil.parseInteger(body,"id");
        if (this.categoryMapper.selectByName(name) != null) {
            throw new BizException(ErrorEnum.ErrorCode.categoryNameRepetition);
        }
        Category record = new Category();
        record.setId(id);
        record.setNameCn(name);
        record.setUpdateTime(LocalDateTime.now());
        return categoryMapper.updateByPrimaryKeySelectiveTwo(record);
    }

    /**
     * 删除类目
     * @param id 类目id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int removeByPrimaryKeySelectiveTwo(Integer id) {
        // 判断一级类目下面有关联类目
        if (categoryMapper.selectByPid(id) != null) {
            throw new BizException(ErrorEnum.ErrorCode.categoryNotDelete);
        }
        // 判断类目是否被商品使用
        if (this.productMapper.selectByPrimaryKeyByCategoryId(id) != null) {
            throw new BizException(ErrorEnum.ErrorCode.categoryNotDelete);
        }
        Category record = new Category();
        record.setId(id);
        record.setDeleted(true);
        record.setUpdateTime(LocalDateTime.now());
        return categoryMapper.updateByPrimaryKeySelectiveTwo(record);
    }

    public int updateByPrimaryKey(Category record) {
        return categoryMapper.updateByPrimaryKey(record);
    }

}
